package com.ugoodtech.mdcc.core.service.impl;

import com.mysema.query.BooleanBuilder;
import com.ugoodtech.mdcc.core.Constants;
import com.ugoodtech.mdcc.core.domain.*;
import com.ugoodtech.mdcc.core.dto.JsonResponse;
import com.ugoodtech.mdcc.core.dto.ServiceStatChartListResponse;
import com.ugoodtech.mdcc.core.dto.ServiceStatChartResponse;
import com.ugoodtech.mdcc.core.helper.SearchVoId;
import com.ugoodtech.mdcc.core.repository.*;
import com.ugoodtech.mdcc.core.service.DepartmentCoreService;
import com.ugoodtech.mdcc.core.service.SearchPermissionsService;
import com.ugoodtech.mdcc.core.service.ServiceReportService;

import org.apache.commons.beanutils.ConvertUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class ServiceReportServiceImpl implements ServiceReportService {

    @Autowired
    private StationReportRepository stationReportRepository;

    @Autowired
    private DepartmentCoreService departmentCoreService;

    @Autowired
    private DepartmentRepository departmentRepository;

    @Autowired
    private UserProfileRepository userProfileRepository;

    @Autowired
    private StationRepository stationRepository;

    @Autowired
    private CustomerRegularReportRepository customerRegularReportRepository;

    @Autowired
    private SearchPermissionsService searchPermissionsService;

    @Autowired
    private StationColorReportRepository stationColorReportRepository;

    @Override
    public JsonResponse getServiceChart(User user, String province, String city, String brand, String category, String stationName,
                                        Long serviceStartTime, Long serviceEndTime, Long startTime, Long endTime, String serviceType,
                                        Integer serviceNum, String reportStatus,String userName, Boolean type, String serviceReportStatus, Long userId, Boolean paintType,
                                        String customerStat, String customerType, String paintBrand, String productPosition, String stationNum, String department,String payService,String sentTime,String serviceTime) {

        SearchVoId searchVoId;
        UserProfile userProfile = userProfileRepository.findByUserId(user.getId());
        if (user.getUserType().equals(UserType.dealers)) {
            searchVoId = searchPermissionsService.getDealersStationId(userProfile, province, brand);
        } else {
            searchVoId = searchPermissionsService.searchColorReportByProvinceBrand(userProfile, province, brand);
        }
        if (searchVoId.getResultStationId().isEmpty()) {
            return JsonResponse.successResponseWithData(new ServiceStatChartListResponse());
        }


        String[] serviceTypes = null;
        String[] cities = null;
        String[] categories = null;
        String[] reportStatuses = null;
        String[] departments = null;
        String[] serviceReportStatuses = null;
        Long[] customerStats = null;
        Long[] customerTypes = null;
        String[] productPositions = null;
        String[] paintBrands = null;

        if (StringUtils.isNotEmpty(serviceType)){
            serviceTypes = serviceType.split(",");
        }
        if (StringUtils.isNotEmpty(city)){
            cities = city.split(",");
        }
        if (!StringUtils.isEmpty(category)){
            categories = category.split(",");
        }
        if (StringUtils.isNotEmpty(reportStatus)){
            reportStatuses = reportStatus.split(",");
        }
        if (!StringUtils.isEmpty(paintBrand)){
            paintBrands = paintBrand.split(",");
        }
        if (StringUtils.isNotEmpty(department)){
            departments = department.split(",");
        }
        if (StringUtils.isNotEmpty(serviceReportStatus)){
            serviceReportStatuses = serviceReportStatus.split(",");
        }
        if (!StringUtils.isEmpty(productPosition)){
            productPositions = productPosition.split(",");
        }
        if (!StringUtils.isEmpty(customerStat)){
            customerStats = (Long[]) ConvertUtils.convert(customerStat.split(","),Long.class);
        }
        if (!StringUtils.isEmpty(customerType)){
            customerTypes = (Long[]) ConvertUtils.convert(customerType.split(","),Long.class);
        }


        QStationReport qStationReport = QStationReport.stationReport;
        BooleanBuilder builder = new BooleanBuilder();
        builder.and(qStationReport.station.deleted.eq(false));
        builder.and(qStationReport.station.enabled.eq(true));
        builder.and(qStationReport.reportType.eq(Constants.REPORT_TYPE_COMPLETE));
        builder.and(qStationReport.category.eq(Constants.SERVICE_REPORT));
        builder.and(qStationReport.station.checkStation.eq(true));

        builder.and(qStationReport.station.id.in(searchVoId.getResultStationId()));
        //判断维修站名称是否为空
        if (StringUtils.isNotEmpty(stationName)) {
            builder.and(qStationReport.station.name.like("%" + stationName + "%"));
        }
        //判断维修站类型是否为空
        if (categories!=null) {
            builder.and(qStationReport.station.category.in(categories));
        }
        if (paintBrands!=null) {
            BooleanBuilder paintBrandBuilder = new BooleanBuilder();
            for (String pBrand:paintBrands){
                paintBrandBuilder.or(qStationReport.station.paintBrand.like("%" + pBrand + "%"));
            }
            builder.and(paintBrandBuilder);
        }
        if (serviceEndTime != null && serviceEndTime != 0){
            builder.and(qStationReport.startServiceTime.goe(new Date(serviceStartTime)));
        }
        if (serviceStartTime != null && serviceStartTime != 0) {
            builder.and(qStationReport.endServiceTime.lt(new Date(serviceEndTime)));
        }
        if (startTime != null && startTime != 0){
            builder.and(qStationReport.updateTime.goe(new Date(startTime)));
        }
        if(endTime != null && endTime != 0) {
            builder.and(qStationReport.updateTime.lt(new Date(endTime)));
        }
        if (serviceNum != null) {
            builder.and(qStationReport.user.serviceNum.eq(serviceNum));
        }
        if (StringUtils.isNotEmpty(stationNum)){
            builder.and(qStationReport.station.stationNum.eq(stationNum));
        }
        if (paintType != null){
            builder.and(qStationReport.station.isPaint.eq(paintType?1:0));
        }
        if (cities!=null) {
            builder.and(qStationReport.station.city.in(cities));
        }
        if (reportStatuses!=null){
            builder.and(qStationReport.exceptionType.in(reportStatuses));
        }

        if (customerStats != null) {
            builder.and(qStationReport.station.customerStat.in(customerStats));
        }
        if (customerTypes != null) {
            builder.and(qStationReport.station.customerType.in(customerTypes));
        }
        if (productPositions!=null) {
            BooleanBuilder builderOr = new BooleanBuilder();
            for (String str: productPositions) {
                builder.and(qStationReport.station.productPosition.like("%" + str + "%"));
            }
            builder.and(builderOr);
        }
        if (serviceTypes != null || serviceReportStatuses != null ) {
            //先从报告答案中找出所有填写过ids中任何一个id的答案
            QStationRegularServiceReport qStationRegularServiceReport = QStationRegularServiceReport.stationRegularServiceReport;
            BooleanBuilder regularBuilder = new BooleanBuilder();
            regularBuilder.and(qStationRegularServiceReport.deleted.eq(false));
            regularBuilder.and(qStationRegularServiceReport.enabled.eq(true));
            BooleanBuilder builderOr = new BooleanBuilder();
            if (serviceTypes != null) {
                for (String id : serviceTypes) {
                    builderOr.or(qStationRegularServiceReport.answerId.like("%" + id + "%"));
                }
                regularBuilder.and(builderOr);
            }
            if (serviceReportStatuses != null){
                for (String id : serviceReportStatuses) {
                    builderOr.or(qStationRegularServiceReport.answerId.like("%" + id + "%"));
                }
                regularBuilder.and(builderOr);
            }
            List<StationRegularServiceReport> list = (List<StationRegularServiceReport>) stationRegularServiceReportRepository.findAll(regularBuilder);
            if (list == null || list.size()==0){
                return JsonResponse.successResponseWithData(new ServiceStatChartListResponse());
            }
            List<Long> Ids = new ArrayList<>();
            for (StationRegularServiceReport report : list) {
                if (report.getReportId() != null) {
                    Ids.add(Long.parseLong(report.getReportId()));
                }
            }
            builder.and(qStationReport.station.id.in(Ids));
        }

        //判断技术人员名称或者部门是否为空

        if (StringUtils.isNotEmpty(userName) || departments != null) {
            QStationColorReport qStationColorReport = QStationColorReport.stationColorReport;
            QUserProfile qUserProfile = QUserProfile.userProfile;
            BooleanBuilder booleanBuilder = new BooleanBuilder();
            booleanBuilder.and(qUserProfile.deleted.eq(false));
            booleanBuilder.and(qUserProfile.enabled.eq(true));
            booleanBuilder.and(qUserProfile.user.userFlag.in(0,2));
            boolean flag = false;
            if (StringUtils.isNotEmpty(userName)) {
                flag = true;
                booleanBuilder.and(qUserProfile.realName.like("%" + userName + "%"));
            }
            if (departments != null){
                flag = true;
                booleanBuilder.and(qUserProfile.user.userFlag.in(0,2));
                booleanBuilder.and(qUserProfile.user.userType.in(UserType.admin,UserType.dealers,UserType.insiders));
                for (String str:departments){
                    booleanBuilder.or(qUserProfile.departmentList.any().name.eq(str));
                }
            }
            if (flag) {
                List<UserProfile> userProfileList = (List<UserProfile>) userProfileRepository.findAll(booleanBuilder);
                if (userProfileList == null || userProfileList.size() == 0) {
                    return JsonResponse.successResponseWithData(new ServiceStatChartListResponse());
                }
                List<Long> userIds = new ArrayList<>();
                for (UserProfile user1 : userProfileList) {
                    userIds.add(user1.getUser().getId());
                }
                BooleanBuilder colorBuilder = new BooleanBuilder();
                colorBuilder.and(qStationColorReport.deleted.eq(false));
                colorBuilder.and(qStationColorReport.enabled.eq(true));
                colorBuilder.and(qStationColorReport.stationReport.station.report_finished.in(1, 2, 3));
                colorBuilder.and(qStationColorReport.stationReport.user.id.in(userIds));
                List<StationColorReport> list = (List<StationColorReport>) stationColorReportRepository.findAll(colorBuilder);
                if (list == null || list.size() == 0) {
                    return JsonResponse.successResponseWithData(new ServiceStatChartListResponse());
                }
                List<Long> ids = new ArrayList<>();
                for (StationColorReport report : list) {
                    if (report.getReportId() != null) {
                        ids.add(Long.parseLong(report.getReportId()));
                    }
                }
                builder.and(qStationReport.id.in(ids));
            }
        }
        if (payService != null || sentTime!=null || serviceTime!=null){
            QStationColorReport qStationColorReport = QStationColorReport.stationColorReport;
            BooleanBuilder builderStationColor = new BooleanBuilder();
            builderStationColor.and(qStationColorReport.deleted.eq(false));
            builderStationColor.and(qStationColorReport.enabled.eq(true));
            boolean flag = false;
            if (payService!=null){
                flag = true;
                builderStationColor.and(qStationColorReport.answerId.like("%"+payService+"%"));
            }
            if (sentTime!=null){
                flag = true;
                builderStationColor.and(qStationColorReport.answerId.like("%"+sentTime+"%"));
            }
            if (serviceTime!=null){
                flag = true;
                builderStationColor.and(qStationColorReport.answerId.like("%"+serviceTime+"%"));
            }
            if (flag) {
                List<StationColorReport> stationColorReports = (List<StationColorReport>) stationColorReportRepository.findAll(builderStationColor);
                if (stationColorReports == null || stationColorReports.size() == 0) {
                    return JsonResponse.successResponseWithData(new ServiceStatChartListResponse());
                }
                List<Long> Ids = new ArrayList<>();
                for (StationColorReport report : stationColorReports) {
                    Ids.add(report.getStationReport().getStation().getId());
                }
                builder.and(qStationReport.station.id.in(Ids));
            }
        }
        if (type != null) {
            QCustomerRegularReport qCustomerRegularReport = QCustomerRegularReport.customerRegularReport;
            BooleanBuilder builderCustomer = new BooleanBuilder();
            builderCustomer.and(qCustomerRegularReport.deleted.eq(false));
            builderCustomer.and(qCustomerRegularReport.enabled.eq(true));
            builderCustomer.and(qCustomerRegularReport.type.eq(type));
            List<CustomerRegularReport> customerRegularReports = (List<CustomerRegularReport>) customerRegularReportRepository.findAll(builderCustomer);
            if (customerRegularReports == null || customerRegularReports.size()==0){
                return JsonResponse.successResponseWithData(new ServiceStatChartListResponse());
            }
            Long[] ids = new Long[customerRegularReports.size()];
            for (int i = 0; i < customerRegularReports.size(); i++) {
                ids[i] = customerRegularReports.get(i).getRegularReport().getId();
            }
            builder.and(qStationReport.id.in(ids));
        }

        //按照创建时间排序查询
        Sort newSort = new Sort(Sort.Direction.DESC, "creationTime");
        List<StationReport> newStationReportList = (List<StationReport>) stationReportRepository.findAll(builder, newSort);

        ServiceStatChartListResponse newResponse = switchResponse(newStationReportList,province, city, brand, category, stationName, serviceStartTime,
                serviceEndTime, startTime, endTime, serviceType, serviceNum, reportStatus, userName, type,
                serviceReportStatus, paintType,customerStat, customerType, paintBrand, productPosition,
                stationNum, department,payService,sentTime,serviceTime);
        return JsonResponse.successResponseWithData(newResponse);
    }

    @Override
    public JsonResponse getServiceChart(User user, String provinces, String brandname, String stationName, String userName, String departmentIds
            , String category, Long startTime, Long endTime) {
        QStationReport qStationReport = QStationReport.stationReport;
        BooleanBuilder builder = new BooleanBuilder();
        builder.and(qStationReport.station.deleted.eq(false));
        builder.and(qStationReport.station.enabled.eq(true));
        builder.and(qStationReport.reportType.eq(Constants.REPORT_TYPE_COMPLETE));
        builder.and(qStationReport.category.eq(Constants.SERVICE_REPORT));
        builder.and(qStationReport.station.checkStation.eq(true));

        SearchVoId searchVoId;
        UserProfile userProfile = userProfileRepository.findByUserId(user.getId());
        if (user.getUserType().equals(UserType.dealers)) {
            searchVoId = searchPermissionsService.getDealersStationId(userProfile, provinces, brandname);
        } else {
            searchVoId = searchPermissionsService.searchColorReportByProvinceBrand(userProfile, provinces, brandname);
        }
        if (searchVoId.getResultStationId().isEmpty()) {
            return JsonResponse.successResponseWithData(new ServiceStatChartListResponse());
        }
        builder.and(qStationReport.station.id.in(searchVoId.getResultStationId()));
        //判断省份是否为空
        boolean provinceTF = false;
        if (StringUtils.isNotEmpty(provinces)) {
            provinceTF = true;
        }
        //判断品牌是否为空
        boolean brandNameTF = false;
        String[] brandArray = null;
        if (StringUtils.isNotEmpty(brandname)) {
            brandArray = brandname.split(",");
            brandNameTF = true;
        }
        //判断维修站名称是否为空
        boolean stationNameTF = false;
        if (StringUtils.isNotEmpty(stationName)) {
            builder.and(qStationReport.station.name.like("%" + stationName + "%"));
            stationNameTF = true;
        }
        //判断技术人员名称或者部门是否为空
        boolean userNameTF = false;
        boolean departmentIdsTF = false;
        if (StringUtils.isNotEmpty(userName) || StringUtils.isNotEmpty(departmentIds)) {
            List<Long> parementDeparetment = departmentCoreService.parentDepartment();
            QUserProfile qUserProfile = QUserProfile.userProfile;
            BooleanBuilder booleanBuilder = new BooleanBuilder();
            booleanBuilder.and(qUserProfile.deleted.eq(false));
            booleanBuilder.and(qUserProfile.enabled.eq(true));
            booleanBuilder.and(qUserProfile.user.userFlag.in(0,2));
            boolean flag = false;
            List<Long> idList = new ArrayList<>();
            if (StringUtils.isNotEmpty(departmentIds)) {
                flag = true;
                String[] ids = departmentIds.split(",");
                Department department = null;
                for (String id : ids) {
                    if (StringUtils.isNotEmpty(id)) {
                        department = departmentRepository.findOne(Long.valueOf(id));
                        if (department != null) {
                            if (parementDeparetment.contains(Long.valueOf(id))) {
                                List<Long> lowerDepartment = departmentCoreService.getLowerDepartment(Long.valueOf(id));
                                idList.addAll(lowerDepartment);
                            } else {
                                idList.add(Long.valueOf(id));
                            }
                        }
                    }
                }
                booleanBuilder.and(qUserProfile.departmentList.any().id.in(idList));
                departmentIdsTF = true;
            }
            if (StringUtils.isNotEmpty(userName)) {
                flag = true;
                booleanBuilder.and(qUserProfile.realName.like("%" + userName + "%"));
                userNameTF = true;
            }
            if (flag) {
                List<UserProfile> userProfileList = (List<UserProfile>) userProfileRepository.findAll(booleanBuilder);
                idList = new ArrayList<>();
                for (UserProfile userProfile1 : userProfileList) {
                    idList.add(userProfile1.getUser().getId());
                }
                builder.and(qStationReport.user.id.in(idList));
            }
        }
        //判断维修站类型是否为空
        boolean categoryTF = false;
        if (StringUtils.isNotEmpty(category)) {
            builder.and(qStationReport.station.category.like("%" + category + "%"));
            categoryTF = true;
        }
        //判断时间是否为空
        boolean timeTF = false;
        if (startTime != null && startTime != 0 && endTime != null && endTime != 0) {
            builder.and(qStationReport.creationTime.after(new Date(startTime)));
            builder.and(qStationReport.creationTime.before(new Date(endTime)));
            timeTF = true;
        }
        //按照创建时间排序查询
        Sort newSort = new Sort(Sort.Direction.DESC, "creationTime");
        List<StationReport> newStationReportList = (List<StationReport>) stationReportRepository.findAll(builder, newSort);
        List<Station> newStationList = new ArrayList<>();
        //去重
        Map<Station, Integer> newStationMap = new HashMap<>();
        for (StationReport stationReport : newStationReportList) {
            if (newStationMap.containsKey(stationReport.getStation())) {
                continue;
            } else {
                newStationMap.put(stationReport.getStation(), 1);
                newStationList.add(stationReport.getStation());
            }
        }
        /**
         * 为返回人员类型准备
         */
        Map<Long, Integer> stationMap = new HashMap<>();
        for (StationReport report : newStationReportList) {
            Long stationId = report.getStation().getId();
            if (stationMap.containsKey(stationId)) {
                Integer value = stationMap.get(stationId);
                stationMap.put(stationId, value + 1);
            } else {
                stationMap.put(stationId, 1);
            }
        }
        Map<Long, Integer> userMap = new HashMap<>();
        for (StationReport report : newStationReportList) {
            Long userId = report.getUser().getId();
            if (userMap.containsKey(userId)) {
                Integer value = userMap.get(userId);
                userMap.put(userId, value + 1);
            } else {
                userMap.put(userId, 1);
            }
        }
        /**
         * 以下开始判断参数进入不同的方法
         */
        ServiceStatChartListResponse newResponse = new ServiceStatChartListResponse();
        List<ServiceStatChartResponse> newStationNameArray = new ArrayList<>();
        /**
         * 条件数为1
         */
        //省份
        if (provinceTF == true && brandNameTF == false && stationNameTF == false && userNameTF == false && departmentIdsTF == false && categoryTF == false && timeTF == false) {
            newStationNameArray = statByStationName(newStationList, startTime, endTime);
            newResponse.setType("station");
        }
        //站点类型
        if (provinceTF == false && brandNameTF == false && stationNameTF == false && userNameTF == false && departmentIdsTF == false && categoryTF == true && timeTF == false) {
            newStationNameArray = statByStationName(newStationList, startTime, endTime);
            newResponse.setType("station");
        }
        //维修站名称
        if (provinceTF == false && brandNameTF == false && stationNameTF == true && userNameTF == false && departmentIdsTF == false && categoryTF == false && timeTF == false) {
            newStationNameArray = statByStationName(newStationList, startTime, endTime);
            newResponse.setType("station");
        }
        //时间
        if (provinceTF == false && brandNameTF == false && stationNameTF == false && userNameTF == false && departmentIdsTF == false && categoryTF == false && timeTF == true) {
            newStationNameArray = statByStationName(newStationList, startTime, endTime);
            newResponse.setType("station");
        }
        //部门
        if (provinceTF == false && brandNameTF == false && stationNameTF == false && userNameTF == false && departmentIdsTF == true && categoryTF == false && timeTF == false) {
            newStationNameArray = statByUserName_station(userMap, stationMap, startTime, endTime);
            newResponse.setType("user");
        }
        //人员名称
        if (provinceTF == false && brandNameTF == false && stationNameTF == false && userNameTF == true && departmentIdsTF == false && categoryTF == false && timeTF == false) {
            newStationNameArray = statByUserName_station(userMap, stationMap, startTime, endTime);
            newResponse.setType("user");
        }
        //品牌
        if (provinceTF == false && brandNameTF == true && stationNameTF == false && userNameTF == false && departmentIdsTF == false && categoryTF == false && timeTF == false) {
            newStationNameArray = statByBrand_station(stationMap, brandArray, startTime, endTime);
            newResponse.setType("brand");
        }
        /**
         * 条件数为2
         */
        //省份+时间
        if (provinceTF == true && brandNameTF == false && stationNameTF == false && userNameTF == false && departmentIdsTF == false && categoryTF == false && timeTF == true) {
            newStationNameArray = statByStationName(newStationList, startTime, endTime);
            newResponse.setType("station");
        }
        //站点类型+时间
        if (provinceTF == false && brandNameTF == false && stationNameTF == false && userNameTF == false && departmentIdsTF == false && categoryTF == true && timeTF == true) {
            newStationNameArray = statByStationName(newStationList, startTime, endTime);
            newResponse.setType("station");
        }
        //维修站名称+时间
        if (provinceTF == false && brandNameTF == false && stationNameTF == true && userNameTF == false && departmentIdsTF == false && categoryTF == false && timeTF == true) {
            newStationNameArray = statByStationName(newStationList, startTime, endTime);
            newResponse.setType("station");
        }
        //部门+时间
        if (provinceTF == false && brandNameTF == false && stationNameTF == false && userNameTF == false && departmentIdsTF == true && categoryTF == false && timeTF == true) {
            newStationNameArray = statByUserName_station(userMap, stationMap, startTime, endTime);
            newResponse.setType("user");
        }
        //人员+时间
        if (provinceTF == false && brandNameTF == false && stationNameTF == false && userNameTF == true && departmentIdsTF == false && categoryTF == false && timeTF == true) {
            newStationNameArray = statByUserName_station(userMap, stationMap, startTime, endTime);
            newResponse.setType("user");
        }
        //品牌+时间
        if (provinceTF == false && brandNameTF == true && stationNameTF == false && userNameTF == false && departmentIdsTF == false && categoryTF == false && timeTF == true) {
            newStationNameArray = statByBrand_station(stationMap, brandArray, startTime, endTime);
            newResponse.setType("brand");
        }
        //省份+品牌
        if (provinceTF == true && brandNameTF == true && stationNameTF == false && userNameTF == false && departmentIdsTF == false && categoryTF == false && timeTF == false) {
            newStationNameArray = statByBrand_station(stationMap, brandArray, startTime, endTime);
            newResponse.setType("brand");
        }
        //省份+站点类型
        if (provinceTF == true && brandNameTF == false && stationNameTF == false && userNameTF == false && departmentIdsTF == false && categoryTF == true && timeTF == false) {
            newStationNameArray = statByStationName(newStationList, startTime, endTime);
            newResponse.setType("station");
        }
        //品牌+站点类型
        if (provinceTF == false && brandNameTF == true && stationNameTF == false && userNameTF == false && departmentIdsTF == false && categoryTF == true && timeTF == false) {
            newStationNameArray = statByBrand_station(stationMap, brandArray, startTime, endTime);
            newResponse.setType("brand");
        }
        /**
         * 条件数为3
         */
        //省份+品牌+时间
        if (provinceTF && brandNameTF == true && stationNameTF == false && userNameTF == false && departmentIdsTF == false && categoryTF == false && timeTF == true) {
            newStationNameArray = statByBrand_station(stationMap, brandArray, startTime, endTime);
            newResponse.setType("brand");
        }
        //省份+站点类型+时间
        if (provinceTF && brandNameTF == false && stationNameTF == false && userNameTF == false && departmentIdsTF == false && categoryTF == true && timeTF == true) {
            newStationNameArray = statByStationName(newStationList, startTime, endTime);
            newResponse.setType("station");
        }
        //品牌+站点类型+时间
        if (provinceTF == false && brandNameTF == true && stationNameTF == false && userNameTF == false && departmentIdsTF == false && categoryTF == true && timeTF == true) {
            newStationNameArray = statByBrand_station(stationMap, brandArray, startTime, endTime);
            newResponse.setType("brand");
        }
        //省份+品牌+站点类型
        if (provinceTF && brandNameTF && stationNameTF == false && userNameTF == false && departmentIdsTF == false && categoryTF == true && timeTF == false) {
            newStationNameArray = statByBrand_station(stationMap, brandArray, startTime, endTime);
            newResponse.setType("brand");
        }
        newResponse.setChartResponseList(newStationNameArray);
        return JsonResponse.successResponseWithData(newResponse);
    }

    @Autowired
    private StationRegularServiceReportRepository stationRegularServiceReportRepository;

    private List<ServiceStatChartResponse> statByStationName(List<Station> stationList, Long startTime, Long endTime) {
        List<ServiceStatChartResponse> stationArray = new ArrayList<>();
        List<Long> stationIdList = new ArrayList<>();
        for (Station station : stationList) {
            stationIdList.add(station.getId());
        }
        QStationReport qStationReport = QStationReport.stationReport;
        BooleanBuilder builder = new BooleanBuilder();
        builder.and(qStationReport.deleted.eq(false));
        builder.and(qStationReport.enabled.eq(true));
        builder.and(qStationReport.category.eq(Constants.SERVICE_REPORT));
        builder.and(qStationReport.station.id.in(stationIdList));
        List<StationReport> stationReportList = (List<StationReport>) stationReportRepository.findAll(builder);
        if (stationReportList != null && stationReportList.size() > 0) {
            List<StationReport> reportList = new ArrayList<>();
            for (StationReport stationReport : stationReportList) {
                StationRegularServiceReport answer = stationRegularServiceReportRepository.selectAnswer(stationReport.getId(), 354L);
                if (null == answer) {
                    reportList.add(stationReport);
                }
            }
            stationArray = statByStationName_user(reportList, stationList, startTime, endTime);
        }

        return stationArray;
    }

    private ServiceStatChartListResponse switchResponse(List<StationReport> newStationReportList, String province, String city, String brand, String category, String stationName,
                                                        Long serviceStartTime, Long serviceEndTime, Long startTime, Long endTime, String serviceType,
                                                        Integer serviceNum, String reportStatus,String userName, Boolean type, String serviceReportStatus, Boolean paintType,
                                                        String customerStat, String customerType, String paintBrand, String productPosition, String stationNum, String department,String payService,String sentTime,String serviceTime){

        String[] brands = null;
        if (!StringUtils.isEmpty(brand)){
            brands = brand.split(",");
        }
        List<Station> newStationList = new ArrayList<>();
        //去重
        Map<Station, Integer> newStationMap = new HashMap<>();
        for (StationReport stationReport : newStationReportList) {
            if (newStationMap.containsKey(stationReport.getStation())) {
                continue;
            } else {
                newStationMap.put(stationReport.getStation(), 1);
                newStationList.add(stationReport.getStation());
            }
        }
        /**
         * 为返回人员类型准备
         */
        Map<Long, Integer> stationMap = new HashMap<>();
        for (StationReport report : newStationReportList) {
            Long stationId = report.getStation().getId();
            if (stationMap.containsKey(stationId)) {
                Integer value = stationMap.get(stationId);
                stationMap.put(stationId, value + 1);
            } else {
                stationMap.put(stationId, 1);
            }
        }
        Map<Long, Integer> userMap = new HashMap<>();
        for (StationReport report : newStationReportList) {
            Long userId1 = report.getUser().getId();
            if (userMap.containsKey(userId1)) {
                Integer value = userMap.get(userId1);
                userMap.put(userId1, value + 1);
            } else {
                userMap.put(userId1, 1);
            }
        }

        /**
         * 以下开始判断参数进入不同的方法
         */
        ServiceStatChartListResponse newResponse = new ServiceStatChartListResponse();
        List<ServiceStatChartResponse> newStationNameArray = new ArrayList<>();
        String typeForResponse = switchType(province, city, brand, category, stationName, serviceStartTime,
                serviceEndTime, startTime, endTime, serviceType, serviceNum, reportStatus, userName, type,
                serviceReportStatus, paintType,customerStat, customerType, paintBrand, productPosition,
                stationNum, department,payService,sentTime,serviceTime);
        if (!typeForResponse.equals("")) {
            switch (typeForResponse) {
                case RESPONSE_TYPE_STATION:
                    newStationNameArray = statByStationName(newStationList, startTime, endTime);
                    newResponse.setType("station");
                    break;
                case RESPONSE_TYPE_BRAND:
                    newStationNameArray = statByBrand_station(stationMap, brands, startTime, endTime);
                    newResponse.setType("brand");
                    break;
                case RESPONSE_TYPE_USER:
                    newStationNameArray = statByUserName_station(userMap, stationMap, startTime, endTime);
                    newResponse.setType("user");
                    break;
            }
            newResponse.setChartResponseList(newStationNameArray);
        }
        return  newResponse;
    }

    final String RESPONSE_TYPE_STATION = "station";
    final String RESPONSE_TYPE_BRAND = "brand";
    final String RESPONSE_TYPE_USER = "user";
    private String switchType(String province, String city, String brand, String category, String stationName,
                              Long serviceStartTime, Long serviceEndTime, Long startTime, Long endTime, String serviceType,
                              Integer serviceNum, String reportStatus,String userName, Boolean type, String serviceReportStatus, Boolean paintType,
                              String customerStat, String customerType, String paintBrand, String productPosition, String stationNum, String department,String payService,String sentTime,String serviceTime){
        if (StringUtils.isNotEmpty(brand)){
            return RESPONSE_TYPE_BRAND;
        }
        if (StringUtils.isNotEmpty(userName)){
            return RESPONSE_TYPE_USER;
        }
        if (StringUtils.isNotEmpty(stationName)){
            return RESPONSE_TYPE_STATION;
        }
        if (serviceStartTime != null && serviceStartTime != 0){
            return RESPONSE_TYPE_USER;
        }
        if (serviceEndTime != null && serviceEndTime != 0){
            return RESPONSE_TYPE_USER;
        }
        if (StringUtils.isNotEmpty(province)){
            return RESPONSE_TYPE_STATION;
        }
        if (StringUtils.isNotEmpty(city)){
            return RESPONSE_TYPE_STATION;
        }
        if (startTime != null && startTime != 0){
            return RESPONSE_TYPE_USER;
        }
        if (endTime != null && endTime != 0){
            return RESPONSE_TYPE_USER;
        }
        if (StringUtils.isNotEmpty(department)){
            return RESPONSE_TYPE_USER;
        }
        if (StringUtils.isNotEmpty(reportStatus)){
            return RESPONSE_TYPE_USER;
        }
        if (StringUtils.isNotEmpty(customerStat)){
            return RESPONSE_TYPE_STATION;
        }
        if (StringUtils.isNotEmpty(customerType)){
            return RESPONSE_TYPE_STATION;
        }
        if (StringUtils.isNotEmpty(category)){
            return RESPONSE_TYPE_STATION;
        }
        if (StringUtils.isNotEmpty(serviceType)){
            return RESPONSE_TYPE_STATION;
        }
        if (serviceNum != null){
            return RESPONSE_TYPE_STATION;
        }
        if (type != null){
            return RESPONSE_TYPE_STATION;
        }
        if (StringUtils.isNotEmpty(serviceReportStatus)){
            return RESPONSE_TYPE_USER;
        }
        if (paintType != null){
            return RESPONSE_TYPE_STATION;
        }
        if (StringUtils.isNotEmpty(serviceTime)){
            return RESPONSE_TYPE_BRAND;
        }
        if (StringUtils.isNotEmpty(sentTime)){
            return RESPONSE_TYPE_BRAND;
        }
        if (StringUtils.isNotEmpty(payService)){
            return RESPONSE_TYPE_USER;
        }
        if (StringUtils.isNotEmpty(productPosition)){
            return RESPONSE_TYPE_BRAND;
        }
        if (StringUtils.isNotEmpty(paintBrand)){
            return RESPONSE_TYPE_BRAND;
        }
        if (StringUtils.isNotEmpty(stationNum)){
            return RESPONSE_TYPE_STATION;
        }
        return "";
    }

    /**
     * 通过维修站名称作为搜索条件
     */
    private List<ServiceStatChartResponse> statByStationName_user(List<StationReport> stationReportList, List<Station> stationList, Long startTime, Long endTime) {
        List<ServiceStatChartResponse> responseList = new ArrayList<>();
        Map<Long, Integer> userMap = new HashMap<>();
        for (StationReport report : stationReportList) {
            //统计技术人员姓名以及服务次数
            Long userId = report.getUser().getId();
            if (userMap.containsKey(userId)) {
                Integer value = userMap.get(userId);
                userMap.put(userId, value + 1);
            } else {
                userMap.put(userId, 1);
            }
        }
        for (Station station : stationList) {
            List<String[]> strList = new ArrayList<>();
            for (Map.Entry<Long, Integer> entry : userMap.entrySet()) {
                String[] str = new String[5];
                UserProfile userProfile = userProfileRepository.findByUserId(entry.getKey());
                String realName = "";
                if (userProfile != null && StringUtils.isNotEmpty(userProfile.getRealName())) {
                    realName = userProfile.getRealName();
                }

                QStationReport qStationReport = QStationReport.stationReport;
                BooleanBuilder builder = new BooleanBuilder();
                builder.and(qStationReport.deleted.eq(false));
                builder.and(qStationReport.enabled.eq(true));
                builder.and(qStationReport.station.id.eq(station.getId()));
                builder.and(qStationReport.user.id.eq(entry.getKey()));
                builder.and(qStationReport.category.eq(Constants.SERVICE_REPORT));
                if (startTime != null && endTime != null) {
                    builder.and(qStationReport.creationTime.after(new Date(startTime)));
                    builder.and(qStationReport.creationTime.before(new Date(endTime)));
                }
                List<StationReport> reportList = (List<StationReport>) stationReportRepository.findAll(builder);
                if (reportList.size() <= 0) {
                    continue;
                }


                int serviceNum = reportList.size();
                String[] numValue = statServiceNum(reportList);
                int serviceTypeNum = Integer.valueOf(numValue[0]);
                int serviceDayNum = Integer.valueOf(numValue[1]);
                str[0] = realName;
                str[1] = String.valueOf(serviceNum);
                str[2] = String.valueOf(serviceDayNum);
                str[3] = String.valueOf(serviceTypeNum);
                str[4] = String.valueOf(countCustomerBy_Station(station, entry.getKey(), startTime, endTime));
                strList.add(str);
            }
            ServiceStatChartResponse response = new ServiceStatChartResponse();
            response.setName(station.getName());
            response.setStrList(strList);
            String[] countNum = countNum(strList);
            response.setCountArray(countNum);
            responseList.add(response);
        }
        return responseList;
    }

    /**
     * 维修站名称作为搜索条件 统计出服务天数以及服务项目数量
     */
    private String[] statServiceNum(List<StationReport> reportList) {
        String[] numValue = new String[3];
        Map<String, Integer> valueMap = new HashMap<>();
        int dayValue = 0;
        Map<Long, Integer> userMap = new HashMap<>();
        for (StationReport report : reportList) {
            if (StringUtils.isNotEmpty(report.getServiceTypAnswerIds())) {
                String[] strLength = report.getServiceTypAnswerIds().split(",");
                for (String str : strLength) {
                    if (StringUtils.isNotEmpty(str)) {
                        valueMap.put(str, 1);
                    }
                }
            }
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat(Constants.DATE_FORMAT);
            userMap.put(report.getUser().getId(), 1);
            Long startDate = report.getStartServiceTime().getTime();
            Long endDate = report.getEndServiceTime().getTime();
            String startDateStr = simpleDateFormat.format(startDate) + " 00:00:00";
            String endDateStr = simpleDateFormat.format(endDate) + " 23:59:59";
            simpleDateFormat = new SimpleDateFormat(Constants.DEFAULT_DATE_FORMAT);
            try {
                startDate = simpleDateFormat.parse(startDateStr).getTime();
                endDate = simpleDateFormat.parse(endDateStr).getTime();
            } catch (ParseException e) {
                e.printStackTrace();
            }
            Long subDate = endDate - startDate;
            if (subDate <= Constants.OneDayTime) {
                dayValue += 1;
            } else if (subDate > Constants.OneDayTime) {
                double sumValue = Double.valueOf(subDate) / Double.valueOf(Constants.OneDayTime) + dayValue;
                double subNum = Math.ceil(sumValue);
                dayValue += subNum;
            }
        }
        numValue[0] = String.valueOf(valueMap.size());
        numValue[1] = String.valueOf(dayValue);
        numValue[2] = String.valueOf(userMap.size());
        return numValue;
    }

    /**
     * 通过技术人员名称作为搜索条件
     */
    private List<ServiceStatChartResponse> statByUserName_station(Map<Long, Integer> userMap, Map<Long, Integer> stationMap, Long startTime, Long endTime) {
        List<ServiceStatChartResponse> responseList = new ArrayList<>();
        for (Map.Entry<Long, Integer> userId : userMap.entrySet()) {
            List<String[]> strList = new ArrayList<>();
            for (Map.Entry<Long, Integer> stationId : stationMap.entrySet()) {
                String[] str = new String[5];
                Station station = stationRepository.findOne(stationId.getKey());
                String stationName = "";
                if (station != null && StringUtils.isNotEmpty(station.getName())) {
                    stationName = station.getName();
                }
                QStationReport qStationReport = QStationReport.stationReport;
                BooleanBuilder builder = new BooleanBuilder();
                builder.and(qStationReport.deleted.eq(false));
                builder.and(qStationReport.enabled.eq(true));
                builder.and(qStationReport.station.id.eq(stationId.getKey()));
                builder.and(qStationReport.user.id.eq(userId.getKey()));
                builder.and(qStationReport.category.eq(Constants.SERVICE_REPORT));
                if (startTime != null && endTime != null) {
                    builder.and(qStationReport.creationTime.after(new Date(startTime)));
                    builder.and(qStationReport.creationTime.before(new Date(endTime)));
                }
                List<StationReport> reportList = (List<StationReport>) stationReportRepository.findAll(builder);
                if (reportList.size() <= 0) {
                    continue;
                }
                List<StationReport> stationReportList = new ArrayList<>();
                for (StationReport stationReport : reportList) {
                    StationRegularServiceReport answer = stationRegularServiceReportRepository.selectAnswer(stationReport.getId(), 354L);
                    if (null == answer) {
                        stationReportList.add(stationReport);
                    }
                }
                String[] numValue = statServiceNum(stationReportList);
                int serviceTypeNum = Integer.valueOf(numValue[0]);
                int serviceDayNum = Integer.valueOf(numValue[1]);
                str[0] = stationName;
                str[1] = String.valueOf(stationReportList.size());
                str[2] = String.valueOf(serviceDayNum);
                str[3] = String.valueOf(serviceTypeNum);
                str[4] = String.valueOf(countCustomerBy_Station(station, userId.getKey(), startTime, endTime));
                strList.add(str);
            }
            UserProfile userProfile = userProfileRepository.findByUserId(userId.getKey());
            String realName = "";
            if (userProfile != null && StringUtils.isNotEmpty(userProfile.getRealName())) {
                realName = userProfile.getRealName();
            }
            ServiceStatChartResponse response = new ServiceStatChartResponse();
            response.setName(realName);
            response.setStrList(strList);
            String[] countNum = countNum(strList);
            response.setCountArray(countNum);
            responseList.add(response);
        }
        return responseList;
    }

    /**
     * 通过品牌作为搜索条件
     */
    private List<ServiceStatChartResponse> statByBrand_station(Map<Long, Integer> stationMap, String[] brandArray, Long startTime, Long endTime) {
        List<ServiceStatChartResponse> responseList = new ArrayList<>();

        for (String brand : brandArray) {
            List<String[]> strList = new ArrayList<>();
            for (Map.Entry<Long, Integer> stationId : stationMap.entrySet()) {
                String[] str = new String[6];
                Station station = stationRepository.findOne(stationId.getKey());
                String stationName = "";
                if (station != null && StringUtils.isNotEmpty(station.getName())) {
                    stationName = station.getName();
                }
                QStationReport qStationReport = QStationReport.stationReport;
                BooleanBuilder builder = new BooleanBuilder();
                builder.and(qStationReport.deleted.eq(false));
                builder.and(qStationReport.enabled.eq(true));
                builder.and(qStationReport.station.brand.like("%" + brand + "%"));
                builder.and(qStationReport.station.id.eq(stationId.getKey()));
                builder.and(qStationReport.category.eq(Constants.SERVICE_REPORT));
                if (startTime != null && endTime != null) {
                    builder.and(qStationReport.creationTime.after(new Date(startTime)));
                    builder.and(qStationReport.creationTime.before(new Date(endTime)));
                }
                List<StationReport> reportList = (List<StationReport>) stationReportRepository.findAll(builder);
                if (reportList.size() <= 0) {
                    continue;
                }

                List<StationReport> stationReportList = new ArrayList<>();
                for (StationReport stationReport : reportList) {
                    StationRegularServiceReport answer = stationRegularServiceReportRepository.selectAnswer(stationReport.getId(), 354L);
                    if (null == answer) {
                        stationReportList.add(stationReport);
                    }
                }


                String[] numValue = statServiceNum(stationReportList);
                int serviceTypeNum = Integer.valueOf(numValue[0]);
                int serviceDayNum = Integer.valueOf(numValue[1]);
                int userNum = Integer.valueOf(numValue[2]);
                str[0] = stationName;
                str[1] = String.valueOf(userNum);
                str[2] = String.valueOf(stationReportList.size());
                str[3] = String.valueOf(serviceDayNum);
                str[4] = String.valueOf(serviceTypeNum);
                str[5] = String.valueOf(countCustomerBy_Station(station, null, startTime, endTime));
                strList.add(str);
            }
            ServiceStatChartResponse response = new ServiceStatChartResponse();
            response.setName(brand);
            response.setStrList(strList);
            String[] countNum = countNum(strList);
            response.setCountArray(countNum);
            responseList.add(response);
        }
        return responseList;
    }

    /**
     * 通过维修站查询 此维修填写过几次满意度报告
     */
    private Integer countCustomerBy_Station(Station station, Long userId, Long startTime, Long endTime) {
        QCustomerRegularReport qCustomerRegularReport = QCustomerRegularReport.customerRegularReport;
        BooleanBuilder builder = new BooleanBuilder();
        builder.and(qCustomerRegularReport.deleted.eq(false));
        builder.and(qCustomerRegularReport.enabled.eq(true));
        builder.and(qCustomerRegularReport.regularReport.station.id.eq(station.getId()));
        if (userId != null && userId != 0) {
            builder.and(qCustomerRegularReport.regularReport.user.id.eq(userId));
        }
        if (startTime != null && endTime != null) {
            builder.and(qCustomerRegularReport.regularReport.creationTime.after(new Date(startTime)));
            builder.and(qCustomerRegularReport.regularReport.creationTime.before(new Date(endTime)));
        }
        builder.and(qCustomerRegularReport.customerReport.isNotNull());
        List<CustomerRegularReport> customerRegularReportList = (List<CustomerRegularReport>) customerRegularReportRepository.findAll(builder);

        return customerRegularReportList.size();
    }

    /**
     * 计算出合计
     */
    private String[] countNum(List<String[]> strList) {
        String[] countArray = new String[6];
        if (strList.size() <= 0) {
            return countArray;
        }
        if (strList.size() != 0 && strList.get(0) != null && strList.get(0).length != 0) {
            countArray = new String[strList.get(0).length];
        }
        countArray[0] = "合计";
        int num1 = 0;
        int num2 = 0;
        int num3 = 0;
        int num4 = 0;
        int num5 = 0;
        try {
            for (String[] array : strList) {
                num1 += Integer.valueOf(array[1]);
                num2 += Integer.valueOf(array[2]);
                num3 += Integer.valueOf(array[3]);
                num4 += Integer.valueOf(array[4]);
                if (array.length == 6) {
                    num5 += Integer.valueOf(array[5]);
                }
            }
            countArray[1] = String.valueOf(num1);
            countArray[2] = String.valueOf(num2);
            countArray[3] = String.valueOf(num3);
            countArray[4] = String.valueOf(num4);
            if (strList.get(0).length == 6) {
                countArray[5] = String.valueOf(num5);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return countArray;
    }

}
